//
//  WHQuestionDealController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2019/1/6.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHQuestionDealController.h"
#import "WHTransNumberCell.h"
#import "WHExpressInfoCell.h"
#import "WHScanController.h"
#import "WHRootNavigationController.h"
#import "WHExpressSelectView.h"

@interface WHQuestionDealController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *dataTableView;
@property (nonatomic, copy) NSString *exressNumber; // 运单号
@property (nonatomic, copy) NSString *status; // 状态
@property (nonatomic, strong) NSArray *statusArray;

@end

@implementation WHQuestionDealController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _statusArray = @[@"拒收", @"退回", @"代收贷款", @"错分", @"改地址", @"外包装破损", @"内件破损", @"手机号错误", @"面单错误"];
    self.navigationItem.title = @"问题件处理";
    [self setUpQuestinDealUI];
}

- (void)setUpQuestinDealUI {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    [self.view addSubview:dataTableView];
    
    [dataTableView registerClass:[WHTransNumberCell class] forCellReuseIdentifier:NSStringFromClass([WHTransNumberCell class])];
    [dataTableView registerClass:[WHExpressInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHExpressInfoCell class])];
    
    dataTableView.tableFooterView = [self tableFooterView];
    dataTableView.backgroundColor = CViewBgMainColor;
    dataTableView.separatorInset = UIEdgeInsetsMake(0, KNormalSpace, 0, -KNormalSpace);
    dataTableView.separatorColor = CLineColor;
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top).offset(kTopHeight);
    }];
    
    _dataTableView = dataTableView;
}

- (UIView *)tableFooterView {
    UIView *tableFooterView = [[UIView alloc] init];
    tableFooterView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(85));
    
    UIView *gapView = [[UIView alloc] init];
    [tableFooterView addSubview:gapView];
    gapView.backgroundColor = CLineColor;
    gapView.frame = CGRectMake(0, 0, KScreenWidth, 0.5);
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tableFooterView addSubview:submitButton];
    [submitButton setBackgroundImage:[UIImage imageWithColor:CMDarkOrangeColor] forState:UIControlStateNormal];
    submitButton.frame = CGRectMake(kRealwidth(32), kRealwidth(20), KScreenWidth-2*kRealwidth(32), kRealwidth(45));
    NSString *submitStr = @"上报";
    NSAttributedString *submitAttributeStr = [[NSAttributedString alloc] initWithString:submitStr attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [submitButton setAttributedTitle:submitAttributeStr forState:UIControlStateNormal];
    [submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    ViewRadius(submitButton, kRealwidth(45)/2);
    
    return tableFooterView;
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.row == 0) {
        WHTransNumberCell *numberCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHTransNumberCell class]) forIndexPath:indexPath];
        numberCell.inputTextField.placeholder = @"运单号";
        numberCell.inputTextField.text = self.exressNumber;
        kWeakSelf(self);
        numberCell.textChangeBlock = ^(NSString *text) {
            weakself.exressNumber = text;
        };
        numberCell.beginScan = ^{
            [weakself beginScan];
        };
        numberCell.inputTextField.keyboardType = UIKeyboardTypeDefault;
        cell = numberCell;
    } else if (indexPath.row == 1) {
        WHExpressInfoCell *expressInfoCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHExpressInfoCell class]) forIndexPath:indexPath];
        expressInfoCell.expressNameLabel.text = @"状态";
        if (self.status) {
            expressInfoCell.courierLabel.text = self.status;
        } else {
            expressInfoCell.courierLabel.text = @"";
        }
        
        cell = expressInfoCell;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(55);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1) {
        
        [self.view endEditing:YES];
        kWeakSelf(self);
        [self selectExpressBy:_statusArray headerTitle:@"请选择状态" bottomTitle:@"完成" selectExpress:^(NSInteger selectIndex) {
            weakself.status = weakself.statusArray[selectIndex];
            [weakself.dataTableView reloadData];
        }];
    }
}

#pragma mark - —————— 事件 ——————

- (void)selectExpressBy:(NSArray *)dataArray headerTitle:(NSString *)headerTitle bottomTitle:(NSString *)bottomTitle selectExpress:(selectExpress)select {
    WHExpressSelectView *expressSelectView = [[WHExpressSelectView alloc] initWithArray:dataArray headerTitle:headerTitle bottomTitle:bottomTitle];
    expressSelectView.selectExpress = select;
    [expressSelectView show];
}

- (void)submit:(UIButton *)button {
    [self.view endEditing:YES];
    if (!self.exressNumber) {
        [WHView showHudMsg:@"请完善运单号"];
        return;
    }
    if (!self.status) {
        [WHView showHudMsg:@"请选择状态"];
        return;
    }
    [self updateStatus];
}

- (void)beginScan {
    [self.view endEditing:YES];
    WHScanController *scan = [[WHScanController alloc] init];
    WHRootNavigationController *navi = [[WHRootNavigationController alloc] initWithRootViewController:scan];
    [self presentViewController:navi animated:YES completion:nil];
    kWeakSelf(self);
    scan.outPutStr = ^(NSString *dataStr) {
        [weakself gridOutputStr:dataStr];
    };
}

#pragma mark - —————— 处理扫描结果 ——————

- (void)gridOutputStr:(NSString *)dataStr {
    
    if ([self isBarCode:dataStr]) {
        self.exressNumber = dataStr;
        [self.dataTableView reloadData];
        
        return;
    }
    [WHView showAlertwithTitle:nil message:@"无法识别!" okAction:nil cancelAction:nil];
}

- (BOOL)isBarCode:(NSString *)checkedNumString {
    NSString *barCodeRegex = @"^[a-zA-Z0-9]+$";
    NSPredicate *barCodePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", barCodeRegex];
    return [barCodePredicate evaluateWithObject:checkedNumString];
}

#pragma mark - —————— 接口 ——————
- (void)updateStatus {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_updateStatus);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          self.status, @"failReason",
                          self.exressNumber, @"waybillNum",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                [WHView showAlertwithTitle:nil message:@"上报成功"];
                
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}


@end
